var express = require('express');
var router = express.Router();
var global_config = require("../config.js");
var config = global_config.wechat;
var WechatAPI = require('wechat-api');
// var logger = require('../log4j').logger("wechatApi");
var redis = require("redis");
var client = redis.createClient(global_config.redis.port,
		global_config.redis.ip);
client.auth(global_config.redis.password);
client.select(global_config.redis.database);

// var api = new WechatAPI(config.appid, config.appSecret);
var api = new WechatAPI(config.appid, config.appSecret, function(callback) {
	// 传入一个获取全局token的方法
	client.get("wexin_token", function(err, responseGet) {
		if (err) {
			return callback(err);
		} else {
			return callback(null,JSON.parse(responseGet));
		}
	});
}, function(token, callback) {
	// 请将token存储到全局，跨进程、跨机器级别的全局，比如写到数据库、redis等
	// 这样才能在cluster模式及多机情况下使用，以下为写入到文件的示例
	logger.info("statr set token" + token);
	client.set("wexin_token", JSON.stringify(token),callback());

});


router.get('/accessToken', function(req, res, next) {
	console.log("授权来源："+req.headers.host+req.url);
  res.setTimeout(10000, function() {
      console.error("响应超时。accessToken");
      res.render('timeout', {});
    });
	api.getLatestToken(function(err, token) {
		// console.info("token"+token);
		res.send(token);
	});
});

router.get('/jsconfig', function(req, res, next) {
	console.log("授权来源："+req.headers.host+req.url);
  res.setTimeout(10000, function() {
      console.error("响应超时。jsconfig");
      res.render('timeout', {});
    });
	var url = req.query.url;
	var param = {
		debug : false,
		jsApiList : [ 'onMenuShareTimeline', 'onMenuShareAppMessage' ],
		url : url
	};
	api.getJsConfig(param, function(err, result) {
		if (err) {
			logger.error(err);
			res.send(err);

		} else {
			res.send(result);
		}
	});
});
module.exports = router;
